<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>

	
		<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
		<meta http-equiv="Content-Language" content="en-us">

		<title>Django | Testing Django applications | Django Documentation</title>

		<meta name="ROBOTS" content="ALL">
		<meta http-equiv="imagetoolbar" content="no">
		<meta name="MSSmartTagsPreventParsing" content="true">
		<meta name="Copyright" content="This site's design and contents Copyright (c) 2005  Lawrence Journal-World.">

		<meta name="keywords" content="Python, Django, framework, open-source">
		<meta name="description" content="Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.">

		<link href="Django%20%7C%20Testing%20Django%20applications%20%7C%20Django%20Documentation_files/base.css" rel="stylesheet" type="text/css" media="screen">
		<link href="Django%20%7C%20Testing%20Django%20applications%20%7C%20Django%20Documentation_files/print.css" rel="stylesheet" type="text/css" media="print">
      
  
  <style type="text/css" media="screen">
    #docs-search {
      color: #000;
      float: right;
    }
    #docs-search form {
      font-size: 92%;
      margin: 0;
      padding: 1em 1em 0;
      white-space: nowrap;
    }
    form.search ul {
      list-style: none;
      margin: 0;
      padding: 0;
    }
    form.search li {
      display: inline;
      padding-right: 1em;
    }
    form.search .query {
      width: 18em;
    }
  </style>
  <link rel="stylesheet" href="Django%20%7C%20Testing%20Django%20applications%20%7C%20Django%20Documentation_files/pygments.css" type="text/css">

	</head><body id="documentation" class="default">

	<div id="container">
		<div id="header">
			<h1 id="logo"><a href="http://www.djangoproject.com/"><img src="Django%20%7C%20Testing%20Django%20applications%20%7C%20Django%20Documentation_files/hdr_logo.gif" alt="Django"></a></h1>
			<ul id="nav-global">
				<li id="nav-homepage"><a href="http://www.djangoproject.com/">Home</a></li>
				<li id="nav-download"><a href="http://www.djangoproject.com/download/">Download</a></li>
				<li id="nav-documentation"><a href="http://docs.djangoproject.com/">Documentation</a></li>
				<li id="nav-weblog"><a href="http://www.djangoproject.com/weblog/">Weblog</a></li>
				<li id="nav-community"><a href="http://www.djangoproject.com/community/">Community</a></li>
				<li id="nav-code"><a href="http://code.djangoproject.com/">Code</a></li>
			</ul>
		</div>
		<!-- END Header -->
		<div id="billboard">
  <h2><a href="http://docs.djangoproject.com/en/1.0/">Django documentation</a></h2>
</div>
		<div id="columnwrap">
			
		<div id="content-main">
		


  <h2 class="deck">
  
    This document describes Django version 1.0. For development documentation, 
    <a href="http://docs.djangoproject.com/en/dev/topics/testing/">go here</a>.
  
  </h2>
  <div class="section" id="s-module-django.test">
<span id="s-topics-testing"></span><span id="module-django.test"></span><span id="topics-testing"></span><h1>Testing Django applications<a class="headerlink" href="#module-django.test" title="Permalink to this headline">¶</a></h1>
<p>Automated testing is an extremely useful bug-killing tool for the modern
Web developer. You can use a collection of tests – a <strong>test suite</strong> – to
solve, or avoid, a number of problems:</p>
<ul class="simple">
<li>When you’re writing new code, you can use tests to validate your code
works as expected.</li>
<li>When you’re refactoring or modifying old code, you can use tests to
ensure your changes haven’t affected your application’s behavior
unexpectedly.</li>
</ul>
<p>Testing a Web application is a complex task, because a Web application is made
of several layers of logic – from HTTP-level request handling, to form
validation and processing, to template rendering. With Django’s test-execution
framework and assorted utilities, you can simulate requests, insert test data,
inspect your application’s output and generally verify your code is doing what
it should be doing.</p>
<p>The best part is, it’s really easy.</p>
<p>This document is split into two primary sections. First, we explain how to
write tests with Django. Then, we explain how to run them.</p>
<div class="section" id="s-writing-tests">
<span id="writing-tests"></span><h2>Writing tests<a class="headerlink" href="#writing-tests" title="Permalink to this headline">¶</a></h2>
<p>There are two primary ways to write tests with Django, corresponding to the
two test frameworks that ship in the Python standard library. The two
frameworks are:</p>
<ul>
<li><p class="first"><strong>Doctests</strong> – tests that are embedded in your functions’ docstrings and
are written in a way that emulates a session of the Python interactive
interpreter. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">my_func</span><span class="p">(</span><span class="n">a_list</span><span class="p">,</span> <span class="n">idx</span><span class="p">):</span>
    <span class="sd">"""</span>
<span class="sd">    &gt;&gt;&gt; a = ['larry', 'curly', 'moe']</span>
<span class="sd">    &gt;&gt;&gt; my_func(a, 0)</span>
<span class="sd">    'larry'</span>
<span class="sd">    &gt;&gt;&gt; my_func(a, 1)</span>
<span class="sd">    'curly'</span>
<span class="sd">    """</span>
    <span class="k">return</span> <span class="n">a_list</span><span class="p">[</span><span class="n">idx</span><span class="p">]</span>
</pre></div>
</div>
</li>
<li><p class="first"><strong>Unit tests</strong> -- tests that are expressed as methods on a Python class
that subclasses <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">unittest</span>

<span class="k">class</span> <span class="nc">MyFuncTestCase</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">testBasic</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s">'larry'</span><span class="p">,</span> <span class="s">'curly'</span><span class="p">,</span> <span class="s">'moe'</span><span class="p">]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="n">my_func</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="mf">0</span><span class="p">),</span> <span class="s">'larry'</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="n">my_func</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="mf">1</span><span class="p">),</span> <span class="s">'curly'</span><span class="p">)</span>
</pre></div>
</div>
</li>
</ul>
<p>You can choose the test framework you like, depending on which syntax you
prefer, or you can mix and match, using one framework for some of your code and
the other framework for other code. You can also use any <em>other</em> Python test
frameworks, as we'll explain in a bit.</p>
<div class="section" id="s-writing-doctests">
<span id="writing-doctests"></span><h3>Writing doctests<a class="headerlink" href="#writing-doctests" title="Permalink to this headline">¶</a></h3>
<p>Doctests use Python's standard <a class="reference external" href="http://docs.python.org/lib/module-doctest.html">doctest</a> module, which searches your docstrings
for statements that resemble a session of the Python interactive interpreter.
A full explanation of how doctest works is out of the scope of this document;
read Python's official documentation for the details.</p>
<div class="admonition-what-s-a-docstring admonition">
<p class="first admonition-title">What's a <strong>docstring</strong>?</p>
<p>A good explanation of docstrings (and some guidelines for using them
effectively) can be found in <span class="target" id="index-30"></span><a class="reference external" href="http://www.python.org/dev/peps/pep-0257"><strong>PEP 257</strong></a>:</p>
<blockquote>
A docstring is a string literal that occurs as the first statement in
a module, function, class, or method definition.  Such a docstring
becomes the <tt class="docutils literal"><span class="pre">__doc__</span></tt> special attribute of that object.</blockquote>
<p>For example, this function has a docstring that describes what it does:</p>
<div class="highlight-python"><pre>def add_two(num):
  "Return the result of adding two to the provided number."
   return num + 2</pre>
</div>
<p class="last">Because tests often make great documentation, putting tests directly in
your docstrings is an effective way to document <em>and</em> test your code.</p>
</div>
<p>For a given Django application, the test runner looks for doctests in two
places:</p>
<ul class="simple">
<li>The <tt class="docutils literal"><span class="pre">models.py</span></tt> file. You can define module-level doctests and/or a
doctest for individual models. It's common practice to put
application-level doctests in the module docstring and model-level
doctests in the model docstrings.</li>
<li>A file called <tt class="docutils literal"><span class="pre">tests.py</span></tt> in the application directory -- i.e., the
directory that holds <tt class="docutils literal"><span class="pre">models.py</span></tt>. This file is a hook for any and all
doctests you want to write that aren't necessarily related to models.</li>
</ul>
<p>Here is an example model doctest:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># models.py</span>

<span class="k">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Animal</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="sd">"""</span>
<span class="sd">    An animal that knows how to make noise</span>

<span class="sd">    # Create some animals</span>
<span class="sd">    &gt;&gt;&gt; lion = Animal.objects.create(name="lion", sound="roar")</span>
<span class="sd">    &gt;&gt;&gt; cat = Animal.objects.create(name="cat", sound="meow")</span>

<span class="sd">    # Make 'em speak</span>
<span class="sd">    &gt;&gt;&gt; lion.speak()</span>
<span class="sd">    'The lion says "roar"'</span>
<span class="sd">    &gt;&gt;&gt; cat.speak()</span>
<span class="sd">    'The cat says "meow"'</span>
<span class="sd">    """</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mf">20</span><span class="p">)</span>
    <span class="n">sound</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mf">20</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">speak</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">'The </span><span class="si">%s</span><span class="s"> says "</span><span class="si">%s</span><span class="s">"'</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">sound</span><span class="p">)</span>
</pre></div>
</div>
<p>When you <a class="reference internal" href="#running-tests"><em>run your tests</em></a>, the test runner will find this
docstring, notice that portions of it look like an interactive Python session,
and execute those lines while checking that the results match.</p>
<p>In the case of model tests, note that the test runner takes care of creating
its own test database. That is, any test that accesses a database -- by
creating and saving model instances, for example -- will not affect your
production database. However, the database is not refreshed between doctests,
so if your doctest requires a certain state you should consider flushin the
database or loading a fixture. (See the section on fixtures, below, for more
on this.) Note that to use this feature, the database user Django is connecting
as must have <tt class="docutils literal"><span class="pre">CREATE</span> <span class="pre">DATABASE</span></tt> rights.</p>
<p>For more details about how doctest works, see the <a class="reference external" href="http://docs.python.org/lib/module-doctest.html">standard library
documentation for doctest</a>.</p>
</div>
<div class="section" id="s-writing-unit-tests">
<span id="writing-unit-tests"></span><h3>Writing unit tests<a class="headerlink" href="#writing-unit-tests" title="Permalink to this headline">¶</a></h3>
<p>Like doctests, Django's unit tests use a standard library module: <a class="reference external" href="http://docs.python.org/lib/module-unittest.html">unittest</a>.
This module uses a different way of defining tests, taking a class-based
approach.</p>
<p>As with doctests, for a given Django application, the test runner looks for
unit tests in two places:</p>
<ul class="simple">
<li>The <tt class="docutils literal"><span class="pre">models.py</span></tt> file. The test runner looks for any subclass of
<tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> in this module.</li>
<li>A file called <tt class="docutils literal"><span class="pre">tests.py</span></tt> in the application directory -- i.e., the
directory that holds <tt class="docutils literal"><span class="pre">models.py</span></tt>. Again, the test runner looks for any
subclass of <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> in this module.</li>
</ul>
<p>This example <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> subclass is equivalent to the example given
in the doctest section above:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">unittest</span>
<span class="k">from</span> <span class="nn">myapp.models</span> <span class="k">import</span> <span class="n">Animal</span>

<span class="k">class</span> <span class="nc">AnimalTestCase</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">lion</span> <span class="o">=</span> <span class="n">Animal</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"lion"</span><span class="p">,</span> <span class="n">sound</span><span class="o">=</span><span class="s">"roar"</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">cat</span> <span class="o">=</span> <span class="n">Animal</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">"cat"</span><span class="p">,</span> <span class="n">sound</span><span class="o">=</span><span class="s">"meow"</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">testSpeaking</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">lion</span><span class="o">.</span><span class="n">speak</span><span class="p">(),</span> <span class="s">'The lion says "roar"'</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cat</span><span class="o">.</span><span class="n">speak</span><span class="p">(),</span> <span class="s">'The cat says "meow"'</span><span class="p">)</span>
</pre></div>
</div>
<p>When you <a class="reference internal" href="#running-tests"><em>run your tests</em></a>, the default behavior of the
test utility is to find all the test cases (that is, subclasses of
<tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt>) in <tt class="docutils literal"><span class="pre">models.py</span></tt> and <tt class="docutils literal"><span class="pre">tests.py</span></tt>, automatically build a
test suite out of those test cases, and run that suite.</p>
<p>There is a second way to define the test suite for a module: if you define a
function called <tt class="docutils literal"><span class="pre">suite()</span></tt> in either <tt class="docutils literal"><span class="pre">models.py</span></tt> or <tt class="docutils literal"><span class="pre">tests.py</span></tt>, the
Django test runner will use that function to construct the test suite for that
module. This follows the <a class="reference external" href="http://docs.python.org/lib/organizing-tests.html">suggested organization</a> for unit tests. See the
Python documentation for more details on how to construct a complex test
suite.</p>
<p>For more details about <tt class="docutils literal"><span class="pre">unittest</span></tt>, see the <a class="reference external" href="http://docs.python.org/lib/module-unittest.html">standard library unittest
documentation</a>.</p>
</div>
<div class="section" id="s-which-should-i-use">
<span id="which-should-i-use"></span><h3>Which should I use?<a class="headerlink" href="#which-should-i-use" title="Permalink to this headline">¶</a></h3>
<p>Because Django supports both of the standard Python test frameworks, it's up to
you and your tastes to decide which one to use. You can even decide to use
<em>both</em>.</p>
<p>For developers new to testing, however, this choice can seem confusing. Here,
then, are a few key differences to help you decide which approach is right for
you:</p>
<ul>
<li><p class="first">If you've been using Python for a while, <tt class="docutils literal"><span class="pre">doctest</span></tt> will probably feel
more "pythonic". It's designed to make writing tests as easy as possible,
so it requires no overhead of writing classes or methods. You simply put
tests in docstrings. This has the added advantage of serving as
documentation (and correct documentation, at that!).</p>
<p>If you're just getting started with testing, using doctests will probably
get you started faster.</p>
</li>
<li><p class="first">The <tt class="docutils literal"><span class="pre">unittest</span></tt> framework will probably feel very familiar to developers
coming from Java. <tt class="docutils literal"><span class="pre">unittest</span></tt> is inspired by Java's JUnit, so you'll
feel at home with this method if you've used JUnit or any test framework
inspired by JUnit.</p>
</li>
<li><p class="first">If you need to write a bunch of tests that share similar code, then
you'll appreciate the <tt class="docutils literal"><span class="pre">unittest</span></tt> framework's organization around
classes and methods. This makes it easy to abstract common tasks into
common methods. The framework also supports explicit setup and/or cleanup
routines, which give you a high level of control over the environment
in which your test cases are run.</p>
</li>
</ul>
<p>Again, remember that you can use both systems side-by-side (even in the same
app). In the end, most projects will eventually end up using both. Each shines
in different circumstances.</p>
</div>
</div>
<div class="section" id="s-id1">
<span id="s-running-tests"></span><span id="id1"></span><span id="running-tests"></span><h2>Running tests<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
<p>Once you've written tests, run them using your project's <tt class="docutils literal"><span class="pre">manage.py</span></tt>
utility:</p>
<div class="highlight-python"><pre>$ ./manage.py test</pre>
</div>
<p>By default, this will run every test in every application in
<a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-INSTALLED_APPS"><tt class="xref docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>. If you only want to run tests for a particular
application, add the application name to the command line. For example, if your
<a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-INSTALLED_APPS"><tt class="xref docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> contains <tt class="docutils literal"><span class="pre">'myproject.polls'</span></tt> and
<tt class="docutils literal"><span class="pre">'myproject.animals'</span></tt>, you can run the <tt class="docutils literal"><span class="pre">myproject.animals</span></tt> unit tests alone
with this command:</p>
<div class="highlight-python"><pre>$ ./manage.py test animals</pre>
</div>
<p>Note that we used <tt class="docutils literal"><span class="pre">animals</span></tt>, not <tt class="docutils literal"><span class="pre">myproject.animals</span></tt>.</p>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> You can now choose which test to run.</div>
<p>If you use unit tests, as opposed to
doctests, you can be even <em>more</em> specific in choosing which tests to execute.
To run a single test case in an application (for example, the
<tt class="docutils literal"><span class="pre">AnimalTestCase</span></tt> described in the "Writing unit tests" section), add the
name of the test case to the label on the command line:</p>
<div class="highlight-python"><pre>$ ./manage.py test animals.AnimalTestCase</pre>
</div>
<p>And it gets even more granular than that! To run a <em>single</em> test method inside
a test case, add the name of the test method to the label:</p>
<div class="highlight-python"><pre>$ ./manage.py test animals.AnimalTestCase.testFluffyAnimals</pre>
</div>
<div class="section" id="s-the-test-database">
<span id="the-test-database"></span><h3>The test database<a class="headerlink" href="#the-test-database" title="Permalink to this headline">¶</a></h3>
<p>Tests that require a database (namely, model tests) will not use your "real"
(production) database. A separate, blank database is created for the tests.</p>
<p>Regardless of whether the tests pass or fail, the test database is destroyed
when all the tests have been executed.</p>
<p>By default this test database gets its name by prepending <tt class="docutils literal"><span class="pre">test_</span></tt> to the
value of the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-DATABASE_NAME"><tt class="xref docutils literal"><span class="pre">DATABASE_NAME</span></tt></a> setting. When using the SQLite database
engine the tests will by default use an in-memory database (i.e., the database
will be created in memory, bypassing the filesystem entirely!). If you want to
use a different database name, specify the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-TEST_DATABASE_NAME"><tt class="xref docutils literal"><span class="pre">TEST_DATABASE_NAME</span></tt></a>
setting.</p>
<p>Aside from using a separate database, the test runner will otherwise use all of
the same database settings you have in your settings file:
<a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-DATABASE_ENGINE"><tt class="xref docutils literal"><span class="pre">DATABASE_ENGINE</span></tt></a>, <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-DATABASE_USER"><tt class="xref docutils literal"><span class="pre">DATABASE_USER</span></tt></a>, <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-DATABASE_HOST"><tt class="xref docutils literal"><span class="pre">DATABASE_HOST</span></tt></a>,
etc. The test database is created by the user specified by
<a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-DATABASE_USER"><tt class="xref docutils literal"><span class="pre">DATABASE_USER</span></tt></a>, so you'll need to make sure that the given user
account has sufficient privileges to create a new database on the system.</p>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>For fine-grained control over the
character encoding of your test database, use the
<a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-TEST_DATABASE_CHARSET"><tt class="xref docutils literal"><span class="pre">TEST_DATABASE_CHARSET</span></tt></a> setting. If you're using MySQL, you can also
use the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-TEST_DATABASE_COLLATION"><tt class="xref docutils literal"><span class="pre">TEST_DATABASE_COLLATION</span></tt></a> setting to control the particular
collation used by the test database. See the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#ref-settings"><em>settings documentation</em></a> for details of these advanced settings.</p>
</div>
<div class="section" id="s-other-test-conditions">
<span id="other-test-conditions"></span><h3>Other test conditions<a class="headerlink" href="#other-test-conditions" title="Permalink to this headline">¶</a></h3>
<p>Regardless of the value of the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-DEBUG"><tt class="xref docutils literal"><span class="pre">DEBUG</span></tt></a> setting in your configuration
file, all Django tests run with <tt class="xref docutils literal"><span class="pre">DEBUG=False</span></tt>. This is to ensure that
the observed output of your code matches what will be seen in a production
setting.</p>
</div>
<div class="section" id="s-understanding-the-test-output">
<span id="understanding-the-test-output"></span><h3>Understanding the test output<a class="headerlink" href="#understanding-the-test-output" title="Permalink to this headline">¶</a></h3>
<p>When you run your tests, you'll see a number of messages as the test runner
prepares itself. You can control the level of detail of these messages with the
<tt class="docutils literal"><span class="pre">verbosity</span></tt> option on the command line:</p>
<div class="highlight-python"><pre>Creating test database...
Creating table myapp_animal
Creating table myapp_mineral
Loading 'initial_data' fixtures...
No fixtures found.</pre>
</div>
<p>This tells you that the test runner is creating a test database, as described
in the previous section.</p>
<p>Once the test database has been created, Django will run your tests.
If everything goes well, you'll see something like this:</p>
<div class="highlight-python"><pre>----------------------------------------------------------------------
Ran 22 tests in 0.221s

OK</pre>
</div>
<p>If there are test failures, however, you'll see full details about which tests
failed:</p>
<div class="highlight-python"><pre>======================================================================
FAIL: Doctest: ellington.core.throttle.models
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/dev/django/test/doctest.py", line 2153, in runTest
    raise self.failureException(self.format_failure(new.getvalue()))
AssertionError: Failed doctest test for myapp.models
  File "/dev/myapp/models.py", line 0, in models

----------------------------------------------------------------------
File "/dev/myapp/models.py", line 14, in myapp.models
Failed example:
    throttle.check("actor A", "action one", limit=2, hours=1)
Expected:
    True
Got:
    False

----------------------------------------------------------------------
Ran 2 tests in 0.048s

FAILED (failures=1)</pre>
</div>
<p>A full explanation of this error output is beyond the scope of this document,
but it's pretty intuitive. You can consult the documentation of Python's
<tt class="docutils literal"><span class="pre">unittest</span></tt> library for details.</p>
<p>Note that the return code for the test-runner script is the total number of
failed and erroneous tests. If all the tests pass, the return code is 0. This
feature is useful if you're using the test-runner script in a shell script and
need to test for success or failure at that level.</p>
</div>
</div>
<div class="section" id="s-testing-tools">
<span id="testing-tools"></span><h2>Testing tools<a class="headerlink" href="#testing-tools" title="Permalink to this headline">¶</a></h2>
<p>Django provides a small set of tools that come in handy when writing tests.</p>
<div class="section" id="s-module-django.test.client">
<span id="module-django.test.client"></span><h3>The test client<a class="headerlink" href="#module-django.test.client" title="Permalink to this headline">¶</a></h3>
<p>The test client is a Python class that acts as a dummy Web browser, allowing
you to test your views and interact with your Django-powered application
programmatically.</p>
<p>Some of the things you can do with the test client are:</p>
<ul class="simple">
<li>Simulate GET and POST requests on a URL and observe the response --
everything from low-level HTTP (result headers and status codes) to
page content.</li>
<li>Test that the correct view is executed for a given URL.</li>
<li>Test that a given request is rendered by a given Django template, with
a template context that contains certain values.</li>
</ul>
<p>Note that the test client is not intended to be a replacement for <a class="reference external" href="http://twill.idyll.org/">Twill</a>,
<a class="reference external" href="http://www.openqa.org/selenium/">Selenium</a>, or other "in-browser" frameworks. Django's test client has
a different focus. In short:</p>
<ul class="simple">
<li>Use Django's test client to establish that the correct view is being
called and that the view is collecting the correct context data.</li>
<li>Use in-browser frameworks such as Twill and Selenium to test <em>rendered</em>
HTML and the <em>behavior</em> of Web pages, namely JavaScript functionality.</li>
</ul>
<p>A comprehensive test suite should use a combination of both test types.</p>
<div class="section" id="s-overview-and-a-quick-example">
<span id="overview-and-a-quick-example"></span><h4>Overview and a quick example<a class="headerlink" href="#overview-and-a-quick-example" title="Permalink to this headline">¶</a></h4>
<p>To use the test client, instantiate <tt class="docutils literal"><span class="pre">django.test.client.Client</span></tt> and retrieve
Web pages:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">from</span> <span class="nn">django.test.client</span> <span class="k">import</span> <span class="n">Client</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">'/login/'</span><span class="p">,</span> <span class="p">{</span><span class="s">'username'</span><span class="p">:</span> <span class="s">'john'</span><span class="p">,</span> <span class="s">'password'</span><span class="p">:</span> <span class="s">'smith'</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span>
<span class="go">200</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/details/'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span><span class="o">.</span><span class="n">content</span>
<span class="go">'&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...'</span>
</pre></div>
</div>
<p>As this example suggests, you can instantiate <tt class="docutils literal"><span class="pre">Client</span></tt> from within a session
of the Python interactive interpreter.</p>
<p>Note a few important things about how the test client works:</p>
<ul>
<li><p class="first">The test client does <em>not</em> require the Web server to be running. In fact,
it will run just fine with no Web server running at all! That's because
it avoids the overhead of HTTP and deals directly with the Django
framework. This helps make the unit tests run quickly.</p>
</li>
<li><p class="first">When retrieving pages, remember to specify the <em>path</em> of the URL, not the
whole domain. For example, this is correct:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/login/'</span><span class="p">)</span>
</pre></div>
</div>
<p>This is incorrect:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'http://www.example.com/login/'</span><span class="p">)</span>
</pre></div>
</div>
<p>The test client is not capable of retrieving Web pages that are not
powered by your Django project. If you need to retrieve other Web pages,
use a Python standard library module such as <a class="reference external" href="http://docs.python.org/lib/module-urllib.html">urllib</a> or <a class="reference external" href="http://docs.python.org/lib/module-urllib2.html">urllib2</a>.</p>
</li>
<li><p class="first">To resolve URLs, the test client uses whatever URLconf is pointed-to by
your <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-ROOT_URLCONF"><tt class="xref docutils literal"><span class="pre">ROOT_URLCONF</span></tt></a> setting.</p>
</li>
<li><p class="first">Although the above example would work in the Python interactive
interpreter, some of the test client's functionality, notably the
template-related functionality, is only available <em>while tests are
running</em>.</p>
<p>The reason for this is that Django's test runner performs a bit of black
magic in order to determine which template was loaded by a given view.
This black magic (essentially a patching of Django's template system in
memory) only happens during test running.</p>
</li>
</ul>
</div>
<div class="section" id="s-making-requests">
<span id="making-requests"></span><h4>Making requests<a class="headerlink" href="#making-requests" title="Permalink to this headline">¶</a></h4>
<p>Use the <tt class="docutils literal"><span class="pre">django.test.client.Client</span></tt> class to make requests. It requires no
arguments at time of construction:</p>
<dl class="class">
<dt id="django.test.client.Client">
<!--[django.test.client.Client]-->class <tt class="descname">Client</tt><a class="headerlink" href="#django.test.client.Client" title="Permalink to this definition">¶</a></dt>
<dd><p>Once you have a <tt class="docutils literal"><span class="pre">Client</span></tt> instance, you can call any of the following
methods:</p>
<dl class="method">
<dt id="django.test.client.Client.get">
<!--[django.test.client.Client.get]--><tt class="descname">get</tt>(<em>path</em>, <em>data={}</em>)<a class="headerlink" href="#django.test.client.Client.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Makes a GET request on the provided <tt class="docutils literal"><span class="pre">path</span></tt> and returns a <tt class="docutils literal"><span class="pre">Response</span></tt>
object, which is documented below.</p>
<p>The key-value pairs in the <tt class="docutils literal"><span class="pre">data</span></tt> dictionary are used to create a GET
data payload. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customers/details/'</span><span class="p">,</span> <span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">'fred'</span><span class="p">,</span> <span class="s">'age'</span><span class="p">:</span> <span class="mf">7</span><span class="p">})</span>
</pre></div>
</div>
<p>...will result in the evaluation of a GET request equivalent to:</p>
<div class="highlight-python"><pre>/customers/details/?name=fred&amp;age=7</pre>
</div>
</dd></dl>

<dl class="method">
<dt id="django.test.client.Client.post">
<!--[django.test.client.Client.post]--><tt class="descname">post</tt>(<em>path</em>, <em>data={}</em>, <em>content_type=MULTIPART_CONTENT</em>)<a class="headerlink" href="#django.test.client.Client.post" title="Permalink to this definition">¶</a></dt>
<dd><p>Makes a POST request on the provided <tt class="docutils literal"><span class="pre">path</span></tt> and returns a
<tt class="docutils literal"><span class="pre">Response</span></tt> object, which is documented below.</p>
<p>The key-value pairs in the <tt class="docutils literal"><span class="pre">data</span></tt> dictionary are used to submit POST
data. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">'/login/'</span><span class="p">,</span> <span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">'fred'</span><span class="p">,</span> <span class="s">'passwd'</span><span class="p">:</span> <span class="s">'secret'</span><span class="p">})</span>
</pre></div>
</div>
<p>...will result in the evaluation of a POST request to this URL:</p>
<div class="highlight-python"><pre>/login/</pre>
</div>
<p>...with this POST data:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">name</span><span class="o">=</span><span class="n">fred</span><span class="o">&amp;</span><span class="n">passwd</span><span class="o">=</span><span class="n">secret</span>
</pre></div>
</div>
<p>If you provide <tt class="docutils literal"><span class="pre">content_type</span></tt> (e.g., <tt class="docutils literal"><span class="pre">text/xml</span></tt> for an XML
payload), the contents of <tt class="docutils literal"><span class="pre">data</span></tt> will be sent as-is in the POST
request, using <tt class="docutils literal"><span class="pre">content_type</span></tt> in the HTTP <tt class="docutils literal"><span class="pre">Content-Type</span></tt> header.</p>
<p>If you don't provide a value for <tt class="docutils literal"><span class="pre">content_type</span></tt>, the values in
<tt class="docutils literal"><span class="pre">data</span></tt> will be transmitted with a content type of
<tt class="docutils literal"><span class="pre">multipart/form-data</span></tt>. In this case, the key-value pairs in <tt class="docutils literal"><span class="pre">data</span></tt>
will be encoded as a multipart message and used to create the POST data
payload.</p>
<p>To submit multiple values for a given key -- for example, to specify
the selections for a <tt class="docutils literal"><span class="pre">&lt;select</span> <span class="pre">multiple&gt;</span></tt> -- provide the values as a
list or tuple for the required key. For example, this value of <tt class="docutils literal"><span class="pre">data</span></tt>
would submit three selected values for the field named <tt class="docutils literal"><span class="pre">choices</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">{</span><span class="s">'choices'</span><span class="p">:</span> <span class="p">(</span><span class="s">'a'</span><span class="p">,</span> <span class="s">'b'</span><span class="p">,</span> <span class="s">'d'</span><span class="p">)}</span>
</pre></div>
</div>
<p>Submitting files is a special case. To POST a file, you need only
provide the file field name as a key, and a file handle to the file you
wish to upload as a value. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">'wishlist.doc'</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="s">'/customers/wishes/'</span><span class="p">,</span> <span class="p">{</span><span class="s">'name'</span><span class="p">:</span> <span class="s">'fred'</span><span class="p">,</span> <span class="s">'attachment'</span><span class="p">:</span> <span class="n">f</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>(The name <tt class="docutils literal"><span class="pre">attachment</span></tt> here is not relevant; use whatever name your
file-processing code expects.)</p>
<p>Note that you should manually close the file after it has been provided
to <tt class="docutils literal"><span class="pre">post()</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.client.Client.login">
<!--[django.test.client.Client.login]--><tt class="descname">login</tt>(<em>**credentials</em>)<a class="headerlink" href="#django.test.client.Client.login" title="Permalink to this definition">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>If your site uses Django's <a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/auth/#topics-auth"><em>authentication system</em></a>
and you deal with logging in users, you can use the test client's
<tt class="docutils literal"><span class="pre">login()</span></tt> method to simulate the effect of a user logging into the
site.</p>
<p>After you call this method, the test client will have all the cookies
and session data required to pass any login-based tests that may form
part of a view.</p>
<p>The format of the <tt class="docutils literal"><span class="pre">credentials</span></tt> argument depends on which
<a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/auth/#authentication-backends"><em>authentication backend</em></a> you're using
(which is configured by your <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-AUTHENTICATION_BACKENDS"><tt class="xref docutils literal"><span class="pre">AUTHENTICATION_BACKENDS</span></tt></a>
setting). If you're using the standard authentication backend provided
by Django (<tt class="docutils literal"><span class="pre">ModelBackend</span></tt>), <tt class="docutils literal"><span class="pre">credentials</span></tt> should be the user's
username and password, provided as keyword arguments:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">login</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s">'fred'</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s">'secret'</span><span class="p">)</span>

<span class="go"># Now you can access a view that's only available to logged-in users.</span>
</pre></div>
</div>
<p>If you're using a different authentication backend, this method may
require different credentials. It requires whichever credentials are
required by your backend's <tt class="docutils literal"><span class="pre">authenticate()</span></tt> method.</p>
<p><tt class="docutils literal"><span class="pre">login()</span></tt> returns <tt class="xref docutils literal"><span class="pre">True</span></tt> if it the credentials were accepted and
login was successful.</p>
<p>Finally, you'll need to remember to create user accounts before you can
use this method. As we explained above, the test runner is executed
using a test database, which contains no users by default. As a result,
user accounts that are valid on your production site will not work
under test conditions. You'll need to create users as part of the test
suite -- either manually (using the Django model API) or with a test
fixture.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.client.Client.logout">
<!--[django.test.client.Client.logout]--><tt class="descname">logout</tt>()<a class="headerlink" href="#django.test.client.Client.logout" title="Permalink to this definition">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>If your site uses Django's <a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/auth/#topics-auth"><em>authentication system</em></a>,
the <tt class="docutils literal"><span class="pre">logout()</span></tt> method can be used to simulate the effect of a user
logging out of your site.</p>
<p>After you call this method, the test client will have all the cookies
and session data cleared to defaults. Subsequent requests will appear
to come from an AnonymousUser.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-testing-responses">
<span id="testing-responses"></span><h4>Testing responses<a class="headerlink" href="#testing-responses" title="Permalink to this headline">¶</a></h4>
<p>The <tt class="docutils literal"><span class="pre">get()</span></tt> and <tt class="docutils literal"><span class="pre">post()</span></tt> methods both return a <tt class="docutils literal"><span class="pre">Response</span></tt> object. This
<tt class="docutils literal"><span class="pre">Response</span></tt> object is <em>not</em> the same as the <tt class="docutils literal"><span class="pre">HttpResponse</span></tt> object returned
Django views; the test response object has some additional data useful for
test code to verify.</p>
<p>Specifically, a <tt class="docutils literal"><span class="pre">Response</span></tt> object has the following attributes:</p>
<dl class="class">
<dt id="django.test.client.Response">
<!--[django.test.client.Response]-->class <tt class="descname">Response</tt><a class="headerlink" href="#django.test.client.Response" title="Permalink to this definition">¶</a></dt>
<dd><dl class="attribute">
<dt id="django.test.client.Response.client">
<!--[django.test.client.Response.client]--><tt class="descname">client</tt><a class="headerlink" href="#django.test.client.Response.client" title="Permalink to this definition">¶</a></dt>
<dd>The test client that was used to make the request that resulted in the
response.</dd></dl>

<dl class="attribute">
<dt id="django.test.client.Response.content">
<!--[django.test.client.Response.content]--><tt class="descname">content</tt><a class="headerlink" href="#django.test.client.Response.content" title="Permalink to this definition">¶</a></dt>
<dd>The body of the response, as a string. This is the final page content as
rendered by the view, or any error message.</dd></dl>

<dl class="attribute">
<dt id="django.test.client.Response.context">
<!--[django.test.client.Response.context]--><tt class="descname">context</tt><a class="headerlink" href="#django.test.client.Response.context" title="Permalink to this definition">¶</a></dt>
<dd><p>The template <tt class="docutils literal"><span class="pre">Context</span></tt> instance that was used to render the template that
produced the response content.</p>
<p>If the rendered page used multiple templates, then <tt class="docutils literal"><span class="pre">context</span></tt> will be a
list of <tt class="docutils literal"><span class="pre">Context</span></tt> objects, in the order in which they were rendered.</p>
</dd></dl>

<dl class="attribute">
<dt id="django.test.client.Response.request">
<!--[django.test.client.Response.request]--><tt class="descname">request</tt><a class="headerlink" href="#django.test.client.Response.request" title="Permalink to this definition">¶</a></dt>
<dd>The request data that stimulated the response.</dd></dl>

<dl class="attribute">
<dt id="django.test.client.Response.status_code">
<!--[django.test.client.Response.status_code]--><tt class="descname">status_code</tt><a class="headerlink" href="#django.test.client.Response.status_code" title="Permalink to this definition">¶</a></dt>
<dd>The HTTP status of the response, as an integer. See <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">RFC2616</a> for a full
list of HTTP status codes.</dd></dl>

<dl class="attribute">
<dt id="django.test.client.Response.template">
<!--[django.test.client.Response.template]--><tt class="descname">template</tt><a class="headerlink" href="#django.test.client.Response.template" title="Permalink to this definition">¶</a></dt>
<dd><p>The <tt class="docutils literal"><span class="pre">Template</span></tt> instance that was used to render the final content. Use
<tt class="docutils literal"><span class="pre">template.name</span></tt> to get the template's file name, if the template was
loaded from a file. (The name is a string such as <tt class="docutils literal"><span class="pre">'admin/index.html'</span></tt>.)</p>
<p>If the rendered page used multiple templates -- e.g., using <a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/templates/#template-inheritance"><em>template
inheritance</em></a> -- then <tt class="docutils literal"><span class="pre">template</span></tt> will be a list of
<tt class="docutils literal"><span class="pre">Template</span></tt> instances, in the order in which they were rendered.</p>
</dd></dl>

</dd></dl>

<p>You can also use dictionary syntax on the response object to query the value
of any settings in the HTTP headers. For example, you could determine the
content type of a response using <tt class="docutils literal"><span class="pre">response['Content-Type']</span></tt>.</p>
</div>
<div class="section" id="s-exceptions">
<span id="exceptions"></span><h4>Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h4>
<p>If you point the test client at a view that raises an exception, that exception
will be visible in the test case. You can then use a standard <tt class="docutils literal"><span class="pre">try...catch</span></tt>
block or <tt class="docutils literal"><span class="pre">unittest.TestCase.assertRaises()</span></tt> to test for exceptions.</p>
<p>The only exceptions that are not visible to the test client are <tt class="docutils literal"><span class="pre">Http404</span></tt>,
<tt class="docutils literal"><span class="pre">PermissionDenied</span></tt> and <tt class="docutils literal"><span class="pre">SystemExit</span></tt>. Django catches these exceptions
internally and converts them into the appropriate HTTP response codes. In these
cases, you can check <tt class="docutils literal"><span class="pre">response.status_code</span></tt> in your test.</p>
</div>
<div class="section" id="s-persistent-state">
<span id="persistent-state"></span><h4>Persistent state<a class="headerlink" href="#persistent-state" title="Permalink to this headline">¶</a></h4>
<p>The test client is stateful. If a response returns a cookie, then that cookie
will be stored in the test client and sent with all subsequent <tt class="docutils literal"><span class="pre">get()</span></tt> and
<tt class="docutils literal"><span class="pre">post()</span></tt> requests.</p>
<p>Expiration policies for these cookies are not followed. If you want a cookie
to expire, either delete it manually or create a new <tt class="docutils literal"><span class="pre">Client</span></tt> instance (which
will effectively delete all cookies).</p>
<p>A test client has two attributes that store persistent state information. You
can access these properties as part of a test condition.</p>
<dl class="attribute">
<dt id="django.test.client.Client.cookies">
<!--[django.test.client.Client.cookies]--><tt class="descclassname">Client.</tt><tt class="descname">cookies</tt><a class="headerlink" href="#django.test.client.Client.cookies" title="Permalink to this definition">¶</a></dt>
<dd>A Python <tt class="docutils literal"><span class="pre">SimpleCookie</span></tt> object, containing the current values of all the
client cookies. See the <a class="reference external" href="http://docs.python.org/lib/module-Cookie.html">Cookie module documentation</a> for more.</dd></dl>

<dl class="attribute">
<dt id="django.test.client.Client.session">
<!--[django.test.client.Client.session]--><tt class="descclassname">Client.</tt><tt class="descname">session</tt><a class="headerlink" href="#django.test.client.Client.session" title="Permalink to this definition">¶</a></dt>
<dd>A dictionary-like object containing session information. See the
<a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/http/sessions/#topics-http-sessions"><em>session documentation</em></a> for full details.</dd></dl>

</div>
<div class="section" id="s-example">
<span id="example"></span><h4>Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h4>
<p>The following is a simple unit test using the test client:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">unittest</span>
<span class="k">from</span> <span class="nn">django.test.client</span> <span class="k">import</span> <span class="n">Client</span>

<span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># Every test needs a client.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># Issue a GET request.</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/details/'</span><span class="p">)</span>

        <span class="c"># Check that the response is 200 OK.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">failUnlessEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mf">200</span><span class="p">)</span>

        <span class="c"># Check that the rendered context contains 5 customers.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">failUnlessEqual</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">context</span><span class="p">[</span><span class="s">'customers'</span><span class="p">]),</span> <span class="mf">5</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-testcase">
<span id="testcase"></span><h3>TestCase<a class="headerlink" href="#testcase" title="Permalink to this headline">¶</a></h3>
<p>Normal Python unit test classes extend a base class of <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt>.
Django provides an extension of this base class:</p>
<dl class="class">
<dt id="django.test.TestCase">
<!--[django.test.TestCase]-->class <tt class="descname">TestCase</tt><a class="headerlink" href="#django.test.TestCase" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>This class provides some additional capabilities that can be useful for testing
Web sites.</p>
<p>Converting a normal <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> to a Django <tt class="docutils literal"><span class="pre">TestCase</span></tt> is easy:
just change the base class of your test from <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> to
<tt class="docutils literal"><span class="pre">django.test.TestCase</span></tt>. All of the standard Python unit test functionality
will continue to be available, but it will be augmented with some useful
additions.</p>
<div class="section" id="s-default-test-client">
<span id="default-test-client"></span><h4>Default test client<a class="headerlink" href="#default-test-client" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<dl class="attribute">
<dt id="django.test.TestCase.client">
<!--[django.test.TestCase.client]--><tt class="descclassname">TestCase.</tt><tt class="descname">client</tt><a class="headerlink" href="#django.test.TestCase.client" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Every test case in a <tt class="docutils literal"><span class="pre">django.test.TestCase</span></tt> instance has access to an
instance of a Django test client. This client can be accessed as
<tt class="docutils literal"><span class="pre">self.client</span></tt>. This client is recreated for each test, so you don't have to
worry about state (such as cookies) carrying over from one test to another.</p>
<p>This means, instead of instantiating a <tt class="docutils literal"><span class="pre">Client</span></tt> in each test:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">unittest</span>
<span class="k">from</span> <span class="nn">django.test.client</span> <span class="k">import</span> <span class="n">Client</span>

<span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/details/'</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">failUnlessEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mf">200</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_index</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">()</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/index/'</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">failUnlessEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mf">200</span><span class="p">)</span>
</pre></div>
</div>
<p>...you can just refer to <tt class="docutils literal"><span class="pre">self.client</span></tt>, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">from</span> <span class="nn">django.test</span> <span class="k">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">SimpleTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_details</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/details/'</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">failUnlessEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mf">200</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_index</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'/customer/index/'</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">failUnlessEqual</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">status_code</span><span class="p">,</span> <span class="mf">200</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-fixture-loading">
<span id="s-topics-testing-fixtures"></span><span id="fixture-loading"></span><span id="topics-testing-fixtures"></span><h4>Fixture loading<a class="headerlink" href="#fixture-loading" title="Permalink to this headline">¶</a></h4>
<dl class="attribute">
<dt id="django.test.TestCase.fixtures">
<!--[django.test.TestCase.fixtures]--><tt class="descclassname">TestCase.</tt><tt class="descname">fixtures</tt><a class="headerlink" href="#django.test.TestCase.fixtures" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A test case for a database-backed Web site isn't much use if there isn't any
data in the database. To make it easy to put test data into the database,
Django's custom <tt class="docutils literal"><span class="pre">TestCase</span></tt> class provides a way of loading <strong>fixtures</strong>.</p>
<p>A fixture is a collection of data that Django knows how to import into a
database. For example, if your site has user accounts, you might set up a
fixture of fake user accounts in order to populate your database during tests.</p>
<p>The most straightforward way of creating a fixture is to use the <tt class="docutils literal"><span class="pre">manage.py</span>
<span class="pre">dumpdata</span></tt> command. This assumes you already have some data in your database.
See the <tt class="xref docutils literal"><span class="pre">dumpdata</span> <span class="pre">documentation</span></tt> for more details.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>If you've ever run <tt class="docutils literal"><span class="pre">manage.py</span> <span class="pre">syncdb</span></tt>, you've already used a fixture
without even knowing it! When you call <tt class="docutils literal"><span class="pre">syncdb</span></tt> in the database for
the first time, Django installs a fixture called <tt class="docutils literal"><span class="pre">initial_data</span></tt>.
This gives you a way of populating a new database with any initial data,
such as a default set of categories.</p>
<p class="last">Fixtures with other names can always be installed manually using the
<tt class="docutils literal"><span class="pre">manage.py</span> <span class="pre">loaddata</span></tt> command.</p>
</div>
<p>Once you've created a fixture and placed it in a <tt class="docutils literal"><span class="pre">fixtures</span></tt> directory in one
of your <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-INSTALLED_APPS"><tt class="xref docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>, you can use it in your unit tests by
specifying a <tt class="docutils literal"><span class="pre">fixtures</span></tt> class attribute on your <tt class="docutils literal"><span class="pre">django.test.TestCase</span></tt>
subclass:</p>
<div class="highlight-python"><pre>from django.test import TestCase
from myapp.models import Animal

class AnimalTestCase(TestCase):
    fixtures = ['mammals.json', 'birds']

    def setUp(self):
        # Test definitions as before.

    def testFluffyAnimals(self):
        # A test that uses the fixtures.</pre>
</div>
<p>Here's specifically what will happen:</p>
<ul class="simple">
<li>At the start of each test case, before <tt class="docutils literal"><span class="pre">setUp()</span></tt> is run, Django will
flush the database, returning the database to the state it was in
directly after <tt class="docutils literal"><span class="pre">syncdb</span></tt> was called.</li>
<li>Then, all the named fixtures are installed. In this example, Django will
install any JSON fixture named <tt class="docutils literal"><span class="pre">mammals</span></tt>, followed by any fixture named
<tt class="docutils literal"><span class="pre">birds</span></tt>. See the <tt class="xref docutils literal"><span class="pre">loaddata</span> <span class="pre">documentation</span></tt> for more
details on defining and installing fixtures.</li>
</ul>
<p>This flush/load procedure is repeated for each test in the test case, so you
can be certain that the outcome of a test will not be affected by another test,
or by the order of test execution.</p>
</div>
<div class="section" id="s-urlconf-configuration">
<span id="urlconf-configuration"></span><h4>URLconf configuration<a class="headerlink" href="#urlconf-configuration" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<dl class="attribute">
<dt id="django.test.TestCase.urls">
<!--[django.test.TestCase.urls]--><tt class="descclassname">TestCase.</tt><tt class="descname">urls</tt><a class="headerlink" href="#django.test.TestCase.urls" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>If your application provides views, you may want to include tests that use the
test client to exercise those views. However, an end user is free to deploy the
views in your application at any URL of their choosing. This means that your
tests can't rely upon the fact that your views will be available at a
particular URL.</p>
<p>In order to provide a reliable URL space for your test,
<tt class="docutils literal"><span class="pre">django.test.TestCase</span></tt> provides the ability to customize the URLconf
configuration for the duration of the execution of a test suite. If your
<tt class="docutils literal"><span class="pre">TestCase</span></tt> instance defines an <tt class="docutils literal"><span class="pre">urls</span></tt> attribute, the <tt class="docutils literal"><span class="pre">TestCase</span></tt> will use
the value of that attribute as the <tt class="docutils literal"><span class="pre">ROOT_URLCONF</span></tt> for the duration of that
test.</p>
<p>For example:</p>
<div class="highlight-python"><pre>from django.test import TestCase

class TestMyViews(TestCase):
    urls = 'myapp.test_urls'

    def testIndexPageView(self):
        # Here you'd test your view using ``Client``.</pre>
</div>
<p>This test case will use the contents of <tt class="docutils literal"><span class="pre">myapp.test_urls</span></tt> as the
URLconf for the duration of the test case.</p>
</div>
<div class="section" id="s-emptying-the-test-outbox">
<span id="s-emptying-test-outbox"></span><span id="emptying-the-test-outbox"></span><span id="emptying-test-outbox"></span><h4>Emptying the test outbox<a class="headerlink" href="#emptying-the-test-outbox" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>If you use Django's custom <tt class="docutils literal"><span class="pre">TestCase</span></tt> class, the test runner will clear the
contents of the test e-mail outbox at the start of each test case.</p>
<p>For more detail on e-mail services during tests, see <a class="reference internal" href="#e-mail-services">E-mail services</a>.</p>
</div>
<div class="section" id="s-assertions">
<span id="assertions"></span><h4>Assertions<a class="headerlink" href="#assertions" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>As Python's normal <tt class="docutils literal"><span class="pre">unittest.TestCase</span></tt> class implements assertion methods
such as <tt class="docutils literal"><span class="pre">assertTrue</span></tt> and <tt class="docutils literal"><span class="pre">assertEquals</span></tt>, Django's custom <tt class="docutils literal"><span class="pre">TestCase</span></tt> class
provides a number of custom assertion methods that are useful for testing Web
applications:</p>
<dl class="method">
<dt id="django.test.TestCase.assertContains">
<!--[django.test.TestCase.assertContains]--><tt class="descclassname">TestCase.</tt><tt class="descname">assertContains</tt>(<em>response</em>, <em>text</em>, <em>count=None</em>, <em>status_code=200</em>)<a class="headerlink" href="#django.test.TestCase.assertContains" title="Permalink to this definition">¶</a></dt>
<dd>Asserts that a <tt class="docutils literal"><span class="pre">Response</span></tt> instance produced the given <tt class="docutils literal"><span class="pre">status_code</span></tt> and
that <tt class="docutils literal"><span class="pre">text</span></tt> appears in the content of the response. If <tt class="docutils literal"><span class="pre">count</span></tt> is
provided, <tt class="docutils literal"><span class="pre">text</span></tt> must occur exactly <tt class="docutils literal"><span class="pre">count</span></tt> times in the response.</dd></dl>

<dl class="method">
<dt id="django.test.TestCase.assertNotContains">
<!--[django.test.TestCase.assertNotContains]--><tt class="descclassname">TestCase.</tt><tt class="descname">assertNotContains</tt>(<em>response</em>, <em>text</em>, <em>status_code=200</em>)<a class="headerlink" href="#django.test.TestCase.assertNotContains" title="Permalink to this definition">¶</a></dt>
<dd>Asserts that a <tt class="docutils literal"><span class="pre">Response</span></tt> instance produced the given <tt class="docutils literal"><span class="pre">status_code</span></tt> and
that <tt class="docutils literal"><span class="pre">text</span></tt> does not appears in the content of the response.</dd></dl>

<dl class="method">
<dt id="django.test.assertFormError">
<!--[django.test.assertFormError]--><tt class="descname">assertFormError</tt>(<em>response</em>, <em>form</em>, <em>field</em>, <em>errors</em>)<a class="headerlink" href="#django.test.assertFormError" title="Permalink to this definition">¶</a></dt>
<dd><p>Asserts that a field on a form raises the provided list of errors when
rendered on the form.</p>
<p><tt class="docutils literal"><span class="pre">form</span></tt> is the name the <tt class="docutils literal"><span class="pre">Form</span></tt> instance was given in the template
context.</p>
<p><tt class="docutils literal"><span class="pre">field</span></tt> is the name of the field on the form to check. If <tt class="docutils literal"><span class="pre">field</span></tt>
has a value of <tt class="xref docutils literal"><span class="pre">None</span></tt>, non-field errors (errors you can access via
<tt class="docutils literal"><span class="pre">form.non_field_errors()</span></tt>) will be checked.</p>
<p><tt class="docutils literal"><span class="pre">errors</span></tt> is an error string, or a list of error strings, that are
expected as a result of form validation.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.assertTemplateUsed">
<!--[django.test.assertTemplateUsed]--><tt class="descname">assertTemplateUsed</tt>(<em>response</em>, <em>template_name</em>)<a class="headerlink" href="#django.test.assertTemplateUsed" title="Permalink to this definition">¶</a></dt>
<dd><p>Asserts that the template with the given name was used in rendering the
response.</p>
<p>The name is a string such as <tt class="docutils literal"><span class="pre">'admin/index.html'</span></tt>.</p>
</dd></dl>

<dl class="method">
<dt id="django.test.assertTemplateNotUsed">
<!--[django.test.assertTemplateNotUsed]--><tt class="descname">assertTemplateNotUsed</tt>(<em>response</em>, <em>template_name</em>)<a class="headerlink" href="#django.test.assertTemplateNotUsed" title="Permalink to this definition">¶</a></dt>
<dd>Asserts that the template with the given name was <em>not</em> used in rendering
the response.</dd></dl>

<dl class="method">
<dt id="django.test.assertRedirects">
<!--[django.test.assertRedirects]--><tt class="descname">assertRedirects</tt>(<em>response</em>, <em>expected_url</em>, <em>status_code=302</em>, <em>target_status_code=200</em>)<a class="headerlink" href="#django.test.assertRedirects" title="Permalink to this definition">¶</a></dt>
<dd>Asserts that the response return a <tt class="docutils literal"><span class="pre">status_code</span></tt> redirect status, it
redirected to <tt class="docutils literal"><span class="pre">expected_url</span></tt> (including any GET data), and the subsequent
page was received with <tt class="docutils literal"><span class="pre">target_status_code</span></tt>.</dd></dl>

</div>
</div>
<div class="section" id="s-e-mail-services">
<span id="e-mail-services"></span><h3>E-mail services<a class="headerlink" href="#e-mail-services" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>If any of your Django views send e-mail using <a class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/email/#topics-email"><em>Django's e-mail
functionality</em></a>, you probably don't want to send e-mail each time
you run a test using that view. For this reason, Django's test runner
automatically redirects all Django-sent e-mail to a dummy outbox. This lets you
test every aspect of sending e-mail -- from the number of messages sent to the
contents of each message -- without actually sending the messages.</p>
<p>The test runner accomplishes this by transparently replacing the normal
<a title="django.core.mail.SMTPConnection" class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/email/#django.core.mail.SMTPConnection"><tt class="xref docutils literal"><span class="pre">SMTPConnection</span></tt></a> class with a different version.
(Don't worry -- this has no effect on any other e-mail senders outside of
Django, such as your machine's mail server, if you're running one.)</p>
<dl class="data">
<dt id="django.core.mail.django.core.mail.outbox">
<!--[django.core.mail.django.core.mail.outbox]--><tt class="descclassname">django.core.mail.</tt><tt class="descname">outbox</tt><a class="headerlink" href="#django.core.mail.django.core.mail.outbox" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>During test running, each outgoing e-mail is saved in
<tt class="docutils literal"><span class="pre">django.core.mail.outbox</span></tt>. This is a simple list of all
<tt class="xref docutils literal"></tt> instances that have been sent.
It does not exist under normal execution conditions, i.e., when you're not
running unit tests. The outbox is created during test setup, along with the
dummy <tt class="xref docutils literal"></tt>. When the test framework is
torn down, the standard <tt class="xref docutils literal"></tt> class is
restored, and the test outbox is destroyed.</p>
<p>The <tt class="docutils literal"><span class="pre">outbox</span></tt> attribute is a special attribute that is created <em>only</em> when
the tests are run. It doesn't normally exist as part of the
<a title="Helpers to easily send e-mail." class="reference external" href="http://docs.djangoproject.com/en/1.0/topics/email/#module-django.core.mail"><tt class="xref docutils literal"><span class="pre">django.core.mail</span></tt></a> module and you can't import it directly. The code
below shows how to access this attribute correctly.</p>
<p>Here's an example test that examines <tt class="docutils literal"><span class="pre">django.core.mail.outbox</span></tt> for length
and contents:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">from</span> <span class="nn">django.core</span> <span class="k">import</span> <span class="n">mail</span>
<span class="k">from</span> <span class="nn">django.test</span> <span class="k">import</span> <span class="n">TestCase</span>

<span class="k">class</span> <span class="nc">EmailTest</span><span class="p">(</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_send_email</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c"># Send message.</span>
        <span class="n">mail</span><span class="o">.</span><span class="n">send_mail</span><span class="p">(</span><span class="s">'Subject here'</span><span class="p">,</span> <span class="s">'Here is the message.'</span><span class="p">,</span>
            <span class="s">'from@example.com'</span><span class="p">,</span> <span class="p">[</span><span class="s">'to@example.com'</span><span class="p">],</span>
            <span class="n">fail_silently</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>

        <span class="c"># Test that one message has been sent.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">mail</span><span class="o">.</span><span class="n">outbox</span><span class="p">),</span> <span class="mf">1</span><span class="p">)</span>

        <span class="c"># Verify that the subject of the first message is correct.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="n">mail</span><span class="o">.</span><span class="n">outbox</span><span class="p">[</span><span class="mf">0</span><span class="p">]</span><span class="o">.</span><span class="n">subject</span><span class="p">,</span> <span class="s">'Subject here'</span><span class="p">)</span>
</pre></div>
</div>
<p>As noted <a class="reference internal" href="#emptying-test-outbox"><em>previously</em></a>, the test outbox is emptied
at the start of every test in a Django <tt class="docutils literal"><span class="pre">TestCase</span></tt>. To empty the outbox
manually, assign the empty list to <tt class="docutils literal"><span class="pre">mail.outbox</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">from</span> <span class="nn">django.core</span> <span class="k">import</span> <span class="n">mail</span>

<span class="c"># Empty the test outbox</span>
<span class="n">mail</span><span class="o">.</span><span class="n">outbox</span> <span class="o">=</span> <span class="p">[]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-using-different-testing-frameworks">
<span id="using-different-testing-frameworks"></span><h2>Using different testing frameworks<a class="headerlink" href="#using-different-testing-frameworks" title="Permalink to this headline">¶</a></h2>
<p>Clearly, <tt class="docutils literal"><span class="pre">doctest</span></tt> and <tt class="docutils literal"><span class="pre">unittest</span></tt> are not the only Python testing
frameworks. While Django doesn't provide explicit support for alternative
frameworks, it does provide a way to invoke tests constructed for an
alternative framework as if they were normal Django tests.</p>
<p>When you run <tt class="docutils literal"><span class="pre">./manage.py</span> <span class="pre">test</span></tt>, Django looks at the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-TEST_RUNNER"><tt class="xref docutils literal"><span class="pre">TEST_RUNNER</span></tt></a>
setting to determine what to do. By default, <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-TEST_RUNNER"><tt class="xref docutils literal"><span class="pre">TEST_RUNNER</span></tt></a> points to
<tt class="docutils literal"><span class="pre">'django.test.simple.run_tests'</span></tt>. This method defines the default Django
testing behavior. This behavior involves:</p>
<ol class="arabic simple">
<li>Performing global pre-test setup.</li>
<li>Creating the test database.</li>
<li>Running <tt class="docutils literal"><span class="pre">syncdb</span></tt> to install models and initial data into the test
database.</li>
<li>Looking for unit tests and doctests in the <tt class="docutils literal"><span class="pre">models.py</span></tt> and
<tt class="docutils literal"><span class="pre">tests.py</span></tt> files in each installed application.</li>
<li>Running the unit tests and doctests that are found.</li>
<li>Destroying the test database.</li>
<li>Performing global post-test teardown.</li>
</ol>
<p>If you define your own test runner method and point <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-TEST_RUNNER"><tt class="xref docutils literal"><span class="pre">TEST_RUNNER</span></tt></a> at
that method, Django will execute your test runner whenever you run
<tt class="docutils literal"><span class="pre">./manage.py</span> <span class="pre">test</span></tt>. In this way, it is possible to use any test framework
that can be executed from Python code.</p>
<div class="section" id="s-defining-a-test-runner">
<span id="defining-a-test-runner"></span><h3>Defining a test runner<a class="headerlink" href="#defining-a-test-runner" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="http://docs.djangoproject.com/en/1.0/releases/1.0/#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>By convention, a test runner should be called <tt class="docutils literal"><span class="pre">run_tests</span></tt>. The only strict
requirement is that it has the same arguments as the Django test runner:</p>
<dl class="function">
<dt id="django.test.simple.run_tests">
<!--[django.test.simple.run_tests]--><tt class="descname">run_tests</tt>(<em>test_labels</em>, <em>verbosity=1</em>, <em>interactive=True</em>, <em>extra_tests=</em><span class="optional">[</span><span class="optional">]</span>)<a class="headerlink" href="#django.test.simple.run_tests" title="Permalink to this definition">¶</a></dt>
<dd><p><tt class="docutils literal"><span class="pre">test_labels</span></tt> is a list of strings describing the tests to be run. A test
label can take one of three forms:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">app.TestCase.test_method</span></tt> -- Run a single test method in a test
case.</li>
<li><tt class="docutils literal"><span class="pre">app.TestCase</span></tt> -- Run all the test methods in a test case.</li>
<li><tt class="docutils literal"><span class="pre">app</span></tt> -- Search for and run all tests in the named application.</li>
</ul>
<p>If <tt class="docutils literal"><span class="pre">test_labels</span></tt> has a value of <tt class="xref docutils literal"><span class="pre">None</span></tt>, the test runner should run
search for tests in all the applications in <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-INSTALLED_APPS"><tt class="xref docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>.</p>
<p><tt class="docutils literal"><span class="pre">verbosity</span></tt> determines the amount of notification and debug information
that will be printed to the console; <tt class="docutils literal"><span class="pre">0</span></tt> is no output, <tt class="docutils literal"><span class="pre">1</span></tt> is normal
output, and <tt class="docutils literal"><span class="pre">2</span></tt> is verbose output.</p>
<p>If <tt class="docutils literal"><span class="pre">interactive</span></tt> is <tt class="xref docutils literal"><span class="pre">True</span></tt>, the test suite has permission to ask the
user for instructions when the test suite is executed. An example of this
behavior would be asking for permission to delete an existing test
database. If <tt class="docutils literal"><span class="pre">interactive</span></tt> is <tt class="xref docutils literal"><span class="pre">False</span></tt>, the test suite must be able to
run without any manual intervention.</p>
<p><tt class="docutils literal"><span class="pre">extra_tests</span></tt> is a list of extra <tt class="docutils literal"><span class="pre">TestCase</span></tt> instances to add to the
suite that is executed by the test runner. These extra tests are run
in addition to those discovered in the modules listed in <tt class="docutils literal"><span class="pre">module_list</span></tt>.</p>
<p>This method should return the number of tests that failed.</p>
</dd></dl>

</div>
<div class="section" id="s-module-django.test.utils">
<span id="module-django.test.utils"></span><h3>Testing utilities<a class="headerlink" href="#module-django.test.utils" title="Permalink to this headline">¶</a></h3>
<p>To assist in the creation of your own test runner, Django provides a number of
utility methods in the <tt class="docutils literal"><span class="pre">django.test.utils</span></tt> module.</p>
<dl class="function">
<dt id="django.test.utils.setup_test_environment">
<!--[django.test.utils.setup_test_environment]--><tt class="descname">setup_test_environment</tt>()<a class="headerlink" href="#django.test.utils.setup_test_environment" title="Permalink to this definition">¶</a></dt>
<dd>Performs any global pre-test setup, such as the installing the
instrumentation of the template rendering system and setting up the dummy
<tt class="docutils literal"><span class="pre">SMTPConnection</span></tt>.</dd></dl>

<dl class="function">
<dt id="django.test.utils.teardown_test_environment">
<!--[django.test.utils.teardown_test_environment]--><tt class="descname">teardown_test_environment</tt>()<a class="headerlink" href="#django.test.utils.teardown_test_environment" title="Permalink to this definition">¶</a></dt>
<dd>Performs any global post-test teardown, such as removing the black magic
hooks into the template system and restoring normal e-mail services.</dd></dl>

<p>The creation module of the database backend (<tt class="docutils literal"><span class="pre">connection.creation</span></tt>) also
provides some utilities that can be useful during testing.</p>
<dl class="function">
<dt id="django.test.utils.create_test_db">
<!--[django.test.utils.create_test_db]--><tt class="descname">create_test_db</tt>(<em>verbosity=1</em>, <em>autoclobber=False</em>)<a class="headerlink" href="#django.test.utils.create_test_db" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new test database and runs <tt class="docutils literal"><span class="pre">syncdb</span></tt> against it.</p>
<p><tt class="docutils literal"><span class="pre">verbosity</span></tt> has the same behavior as in <tt class="docutils literal"><span class="pre">run_tests()</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">autoclobber</span></tt> describes the behavior that will occur if a database with
the same name as the test database is discovered:</p>
<ul class="simple">
<li>If <tt class="docutils literal"><span class="pre">autoclobber</span></tt> is <tt class="xref docutils literal"><span class="pre">False</span></tt>, the user will be asked to approve
destroying the existing database. <tt class="docutils literal"><span class="pre">sys.exit</span></tt> is called if the user
does not approve.</li>
<li>If autoclobber is <tt class="xref docutils literal"><span class="pre">True</span></tt>, the database will be destroyed without
consulting the user.</li>
</ul>
<p>Returns the name of the test database that it created.</p>
<p><tt class="docutils literal"><span class="pre">create_test_db()</span></tt> has the side effect of modifying
<tt class="docutils literal"><span class="pre">settings.DATABASE_NAME</span></tt> to match the name of the test database.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.0:</span> <tt class="docutils literal"><span class="pre">create_test_db()</span></tt> now returns the name of the test database.</div>
</dd></dl>

<dl class="function">
<dt id="django.test.utils.destroy_test_db">
<!--[django.test.utils.destroy_test_db]--><tt class="descname">destroy_test_db</tt>(<em>old_database_name</em>, <em>verbosity=1</em>)<a class="headerlink" href="#django.test.utils.destroy_test_db" title="Permalink to this definition">¶</a></dt>
<dd><p>Destroys the database whose name is in the <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-DATABASE_NAME"><tt class="xref docutils literal"><span class="pre">DATABASE_NAME</span></tt></a> setting
and restores the value of <a class="reference external" href="http://docs.djangoproject.com/en/1.0/ref/settings/#setting-DATABASE_NAME"><tt class="xref docutils literal"><span class="pre">DATABASE_NAME</span></tt></a> to the provided name.</p>
<p><tt class="docutils literal"><span class="pre">verbosity</span></tt> has the same behavior as in <tt class="docutils literal"><span class="pre">run_tests()</span></tt>.</p>
</dd></dl>

</div>
</div>
</div>



<div id="content-secondary">
  <h2 id="comments">Questions/Feedback</h2>
  <p>Having trouble? We'd like to help!</p>
  <ul>
    <li>
      Try the <a href="http://docs.djangoproject.com/en/dev/faq/">FAQ</a> — it's got answers to many common
      questions.
    </li>
    <li>
      Search for information in the <a href="http://groups.google.com/group/django-users/">archives of the
      django-users mailing list</a>, or <a href="http://groups.google.com/group/django-users/">post a question</a>.
    </li>
    <li>
      Ask a question in the <a href="irc://irc.freenode.net/">#django IRC
      channel</a>, or search the <a href="http://oebfare.com/logger/django/">IRC
      logs</a> to see if its been asked before.
    </li>
    <li>
      If you notice errors with this documentation, please <a href="http://code.djangoproject.com/simpleticket?component=Documentation">
      open a ticket</a> and let us know! Please only use the ticket tracker for
      criticisms and improvements on the docs. For tech support, use the
      resources above.
    </li>
  </ul>
</div>

		</div>
		<!-- END #content-main -->
		<div id="content-related" class="sidebar">
		
  
    <h2>Contents</h2>
    
      <ul>
<li><a class="reference external" href="">Testing Django applications</a><ul>
<li><a class="reference external" href="#writing-tests">Writing tests</a><ul>
<li><a class="reference external" href="#writing-doctests">Writing doctests</a></li>
<li><a class="reference external" href="#writing-unit-tests">Writing unit tests</a></li>
<li><a class="reference external" href="#which-should-i-use">Which should I use?</a></li>
</ul>
</li>
<li><a class="reference external" href="#id1">Running tests</a><ul>
<li><a class="reference external" href="#the-test-database">The test database</a></li>
<li><a class="reference external" href="#other-test-conditions">Other test conditions</a></li>
<li><a class="reference external" href="#understanding-the-test-output">Understanding the test output</a></li>
</ul>
</li>
<li><a class="reference external" href="#testing-tools">Testing tools</a><ul>
<li><a class="reference external" href="#module-django.test.client">The test client</a><ul>
<li><a class="reference external" href="#overview-and-a-quick-example">Overview and a quick example</a></li>
<li><a class="reference external" href="#making-requests">Making requests</a></li>
<li><a class="reference external" href="#testing-responses">Testing responses</a></li>
<li><a class="reference external" href="#exceptions">Exceptions</a></li>
<li><a class="reference external" href="#persistent-state">Persistent state</a></li>
<li><a class="reference external" href="#example">Example</a></li>
</ul>
</li>
<li><a class="reference external" href="#testcase">TestCase</a><ul>
<li><a class="reference external" href="#default-test-client">Default test client</a></li>
<li><a class="reference external" href="#fixture-loading">Fixture loading</a></li>
<li><a class="reference external" href="#urlconf-configuration">URLconf configuration</a></li>
<li><a class="reference external" href="#emptying-the-test-outbox">Emptying the test outbox</a></li>
<li><a class="reference external" href="#assertions">Assertions</a></li>
</ul>
</li>
<li><a class="reference external" href="#e-mail-services">E-mail services</a></li>
</ul>
</li>
<li><a class="reference external" href="#using-different-testing-frameworks">Using different testing frameworks</a><ul>
<li><a class="reference external" href="#defining-a-test-runner">Defining a test runner</a></li>
<li><a class="reference external" href="#module-django.test.utils">Testing utilities</a></li>
</ul>
</li>
</ul>
</li>
</ul>

    
  
  
  
    <h2>Search</h2>
    
    <form action="/en/1.0/search/" id="search" class="search">
  <div>
    <input name="cx" value="009763561546736975936:e88ek0eurf4" type="hidden">
    <input name="cof" value="FORID:11" type="hidden">
    <input name="ie" value="UTF-8" type="hidden">
    <input name="hl" value="" type="hidden">
    <input style="background: rgb(255, 255, 255) url(http://www.google.com/coop/intl/en/images/google_custom_search_watermark.gif) no-repeat scroll left center; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" id="id_search_q" class="query" name="q" type="text">
    <input name="sa" class="submit" value="Search" type="submit">
    <ul>
<li><label for="id_search_as_q_0"><input checked="checked" id="id_search_as_q_0" value="more:dev_docs" name="as_q" type="radio"> Latest</label></li>
<li><label for="id_search_as_q_1"><input id="id_search_as_q_1" value="more:1.0_docs" name="as_q" type="radio"> 1.0</label></li>
<li><label for="id_search_as_q_2"><input id="id_search_as_q_2" value="more:0.96_docs" name="as_q" type="radio"> 0.96</label></li>
<li><label for="id_search_as_q_3"><input id="id_search_as_q_3" value="more:all_docs" name="as_q" type="radio"> All</label></li>
</ul>
  </div>
</form>
<script type="text/javascript" src="Django%20%7C%20Testing%20Django%20applications%20%7C%20Django%20Documentation_files/brand.html"></script>
  
  
  
    <h2>Browse</h2>
    <ul>
      
        
          <li>Prev: <a href="http://docs.djangoproject.com/en/1.0/topics/files/">Managing files</a></li>
        
        
          <li>Next: <a href="http://docs.djangoproject.com/en/1.0/topics/auth/">User authentication in Django</a></li>
        
        <li><a href="http://docs.djangoproject.com/en/1.0/contents/">Table of contents</a></li>
        
          <li><a href="http://docs.djangoproject.com/en/1.0/genindex/">General Index</a></li>
        
          <li><a href="http://docs.djangoproject.com/en/1.0/modindex/">Global Module Index</a></li>
        
      
    </ul>
  
  
  
    <h2>You are here:</h2>
    <ul>
      
        <li>
          <a href="http://docs.djangoproject.com/en/1.0/">Django 1.0 documentation</a>
          
            <ul><li><a href="http://docs.djangoproject.com/en/1.0/topics/">Using Django</a>
          
          <ul><li>Testing Django applications</li></ul>
          </li></ul>
        </li>
      
    </ul>
  
  
  
    <h3>Last update:</h3>
    <div>May 23, 2009, 8:15 a.m. (<a href="http://www.timeanddate.com/worldclock/city.html?n=64">CDT</a>)</div>
  

		</div>
		<!-- END #content-related -->

		</div>
		<!-- END #content -->
		<div id="footer">
			<p>© 2005-2009 <a href="http://www.djangoproject.com/foundation/">Django Software Foundation</a> unless otherwise noted. Django is a registered trademark of the Django Software Foundation. 
			Hosting graciously provided by <a href="http://mediatemple.net/">
			<img style="vertical-align: middle; position: relative; top: -1px;" src="Django%20%7C%20Testing%20Django%20applications%20%7C%20Django%20Documentation_files/mt.png" alt="media temple"></a>
			</p>
		</div>
		<!-- END #footer -->
	</div>
	<!-- END #container -->
	</body></html>